<template>
    <div class="content">
        <Form
            class="training-form"
            :label-width="140"
            :model="form"
            :rules="rules"
            ref="form"
        >
            <FormItem label="实训名称" prop="name">
                <Input
                    v-model="form.name"
                    :maxlength="20"
                    placeholder="1到20位，不可重复"
                />
            </FormItem>
            <FormItem label="实训模式" prop="model">
                <RadioGroup v-model="form.model">
                    <Radio
                        v-for="item in trainingMode"
                        :key="item.value"
                        :label="item.value"
                    >
                        {{ item.label }}
                    </Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="实训时间" prop="startTime">
                <DatePicker
                    :value="dateValue"
                    type="datetimerange"
                    format="yyyy-MM-dd HH:mm"
                    placeholder="精确到分"
                    @on-change="handleDateChange"
                ></DatePicker>
            </FormItem>
            <FormItem label="实训任务" prop="task">
                <Select v-model="form.task">
                    <Option
                        v-for="item in taskList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    >
                    </Option>
                </Select>
            </FormItem>
            <FormItem label="实训案例" prop="caseId">
                <RemoteSearch
                    v-model="form.caseId"
                    placeholder="实训案例"
                    :list="caseList"
                    keywordFiled="caseName"
                    valueField="caseId"
                    :labelFieldList="['caseName']"
                    @get-all="caseChange"
                />
            </FormItem>
            <div class="clearfix">
                <div class="form-item">
                    <div class="form-title">难度设置</div>
                    <FormItem label="提醒功能" prop="noticeFunction">
                        <RadioGroup v-model="form.noticeFunction">
                            <Radio :label="1">开启</Radio>
                            <Radio :label="0">关闭</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="校检功能" prop="validateFunction">
                        <RadioGroup v-model="form.validateFunction">
                            <Radio :label="1">开启</Radio>
                            <Radio :label="0">关闭</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="填写帮助" prop="fillHelp">
                        <RadioGroup v-model="form.fillHelp">
                            <Radio :label="1">开启</Radio>
                            <Radio :label="0">关闭</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="单据对照" prop="documentCompare">
                        <RadioGroup v-model="form.documentCompare">
                            <Radio :label="1">开启</Radio>
                            <Radio :label="0">关闭</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="自动填写" prop="autoFill">
                        <RadioGroup v-model="form.autoFill">
                            <Radio :label="1">开启</Radio>
                            <Radio :label="0">关闭</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="可否重做" prop="canRedo">
                        <RadioGroup v-model="form.canRedo">
                            <Radio :label="1">开启</Radio>
                            <Radio :label="0">关闭</Radio>
                        </RadioGroup>
                    </FormItem>
                </div>
                <div class="form-item">
                    <div class="form-title">通过条件</div>
                    <FormItem
                        v-for="(item, i) in form.passCondition"
                        :key="item.type"
                        :label="item.label + '达到'"
                        :prop="`passCondition.${i}.value`"
                        :rules="i ? rules.condition : rules.allCondition"
                    >
                        <Input v-model="item.value" />
                    </FormItem>
                </div>
            </div>
            <div class="form-title">成绩</div>
            <FormItem label="总分" prop="totalScore">
                <Input v-model="form.totalScore" />
            </FormItem>
            <FormItem label="权重" prop="weight">
                <div class="weight-setting">
                    <div class="weight--item">
                        <div class="weight--label">指标</div>
                        <div class="weight--content">
                            权重（100%）
                        </div>
                    </div>
                    <div
                        class="weight--item"
                        v-for="(item) in form.weight"
                        :key="item.type"
                    >
                        <div class="weight--label">{{ item.label }}</div>
                        <div class="weight--content">
                            <Input v-model="item.value" size="small" />
                        </div>
                    </div>
                </div>
            </FormItem>
            <FormItem label="参与班级" prop="classIds">
                <Button type="primary" @click="classModal = true">添加班级</Button>
                <ClassTable
                    v-if="classList.length > 0"
                    style="margin-top: 10px"
                    :data="classList"
                    @delete="delClass"
                />
            </FormItem>
            <FormItem label="课程密码" prop="password">
                <Input v-model="form.password" type="password" autocomplete="new-password" />
            </FormItem>
            <FormItem>
                <div class="submit-footer">
                    <Button type="primary" @click="submit">保存并发布</Button>
                    <Button type="primary" @click="submitSave">保存</Button>
                    <Button @click="cancel">取消</Button>
                </div>
            </FormItem>
        </Form>
        <ClassModal
            v-model="classModal"
            @on-ok="selectClasses"
        />
    </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { transforArr, trainingMode, makerTask, practiceTask, declareTypes } from '@/libs/enums'
import { addTraining, queryTrainingInfo, updateTraining } from '@/api/trainingManage'
import { queryCaseList, queryCaseInfo } from '@/api/caseManage'
import ClassTable from './components/ClassTable'
import ClassModal from './components/ClassModal'

const mkTaskList = transforArr(makerTask)
const ptTaskList = transforArr(practiceTask)

export default {
    inject: ['nextPageReload'],
    components: {
        ClassTable,
        ClassModal
    },
    data () {
        const requiredValid = (rule, value, cb) => {
            return value === void 0 || value === null || value === ''
                ? cb(new Error(rule.message))
                : cb()
        }
        return {
            trainingMode: transforArr(trainingMode),
            form: {
                id: '',
                name: '',
                model: 1,
                startTime: '',
                endTime: '',
                task: '',
                caseId: '',
                noticeFunction: 0,
                validateFunction: 1,
                fillHelp: 1,
                documentCompare: 0,
                autoFill: 0,
                canRedo: 0,
                totalScore: 100,
                classIds: '',
                password: '',
                weight: [
                    { label: '实训报告', value: '', type: '0' }
                ], // 权重
                passCondition: [
                    { label: '所有单据', value: '', type: '0' }
                ] // 通过条件
            },
            rules: {
                name: [
                    { required: true, message: '实训名称必填', trigger: 'blur' },
                    { min: 1, max: 20, message: '校内唯一，1到20位', trigger: 'blur,change' }
                ],
                model: [
                    { required: true, validator: requiredValid, message: '实训模式必填', trigger: 'change' }
                ],
                startTime: [
                    { required: true, validator: requiredValid, message: '实训时间必填', trigger: 'change' }
                ],
                task: [
                    { required: true, validator: requiredValid, message: '实训任务必填', trigger: 'change' }
                ],
                caseId: [
                    { required: true, validator: requiredValid, message: '实训案例必填', trigger: 'change' }
                ],
                noticeFunction: [
                    { required: true, validator: requiredValid, message: '提醒功能必填', trigger: 'change' }
                ],
                validateFunction: [
                    { required: true, validator: requiredValid, message: '校检功能必填', trigger: 'change' }
                ],
                fillHelp: [
                    { required: true, validator: requiredValid, message: '提醒功能必填', trigger: 'change' }
                ],
                documentCompare: [
                    { required: true, validator: requiredValid, message: '单据对照必填', trigger: 'change' }
                ],
                autoFill: [
                    { required: true, validator: requiredValid, message: '自动填写必填', trigger: 'change' }
                ],
                canRedo: [
                    { required: true, validator: requiredValid, message: '可否重做必填', trigger: 'change' }
                ],
                totalScore: [
                    { required: true,
                        validator: (rule, value, cb) => {
                            return /^[1-9]\d*$/.test(value) ? cb() : cb(new Error('请输入正整数'))
                        },
                        trigger: 'change'
                    }
                ],
                weight: [
                    { required: true,
                        validator: (rule, value, cb) => {
                            if (value && value.length) {
                                if (value.some(item => !/^\d+$/.test(item.value))) {
                                    return cb(new Error('请输入大于等于0的整数'))
                                }
                                if (value.reduce((t, item) => (t + Number(item.value)), 0) !== 100) {
                                    return cb(new Error('权重加总必须是100%'))
                                }
                                return cb()
                            } else {
                                return cb(new Error('权重必填'))
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                classIds: [
                    { required: true, message: '班级必填', trigger: 'change' }
                ],
                allCondition: [
                    {
                        validator: (rule, value, cb) => {
                            if (value) {
                                if (!/^[1-9]\d*$/.test(value)) {
                                    return cb(new Error('请输入正整数'))
                                }
                                if (this.form.passCondition.some(item => item.value && item.value != value)) {
                                    return cb(new Error('所有单据通过条件需与单个单据通过条件一致'))
                                }
                            }
                            return cb()
                        },
                        trigger: 'blur'
                    }
                ],
                condition: [
                    {
                        validator: (rule, value, cb) => {
                            if (value && !/^[1-9]\d*$/.test(value)) {
                                return cb(new Error('请输入正整数'))
                            }
                            return cb()
                        },
                        trigger: 'blur'
                    }
                ]
            },
            caseList: [],
            classList: [],
            classModal: false
        }
    },
    computed: {
        dateValue () {
            const { startTime, endTime } = this.form
            return [startTime || '', endTime || '']
        },
        taskList () {
            return this.form.model === 1 ? mkTaskList : ptTaskList
        }
    },
    mounted () {
        const id = this.$route.params.id
        id && this.queryInfo(id)
        this.queryCaseData()
    },
    methods: {
        ...mapMutations(['removeTagNav']),
        queryCaseData () {
            return queryCaseList({
                pageSize: 9999,
                pageNum: 1
            }).then(res => {
                if (res.data.code === '0000') {
                    this.caseList = res.data.data.list
                }
            })
        },
        setWeightPass (answerTypes) {
            const newWeight = []
            const newPassCondition = []
            answerTypes.forEach(type => {
                const name = declareTypes[type]
                newWeight.push({
                    label: `${name}`,
                    type: type,
                    value: ''
                })
                newPassCondition.push({
                    label: `${name}`,
                    type: type,
                    value: ''
                })
                let { weight, passCondition } = this.form
                this.form.passCondition = passCondition.slice(0, 1).concat(newPassCondition)
                this.form.weight = newWeight.concat(weight.slice(weight.length - 1))
            })
        },
        caseChange (data) {
            if (data) {
                const id = data.caseId
                if (!this.caseAnswer) {
                    this.caseAnswer = {}
                }
                const answer = this.caseAnswer[id]
                if (answer) {
                    return this.setWeightPass(answer)
                }
                queryCaseInfo(id).then(res => {
                    if (res.data.code === '0000') {
                        const data = res.data.data
                        const list = data.answerInfoDtoList
                        this.caseAnswer[id] = list.map(item => item.answerType)
                        this.setWeightPass(this.caseAnswer[id])
                    }
                })
            }
        },
        handleDateChange (v) {
            this.form.startTime = v[0] + ':00'
            this.form.endTime = v[1] + ':00'
        },
        selectClasses (v) {
            this.classList = v.slice()
            this.form.classIds = v.map(item => item.classId).join(',')
            this.$refs.form.validateField('classIds')
        },
        delClass (data, i) {
            this.classList.splice(i, 1)
            this.form.classIds = this.classList.map(item => item.classId).join(',')
            this.$refs.form.validateField('classIds')
        },
        queryInfo (id) {
            queryTrainingInfo(id).then(res => {
                if (res.data.code === '0000') {
                    const form = res.data.data
                    try {
                        form.weight = JSON.parse(form.weight)
                    } catch (error) {
                        form.weight = null
                    }
                    try {
                        form.passCondition = JSON.parse(form.passCondition)
                    } catch (error) {
                        form.passCondition = null
                    }
                    if (!Array.isArray(form.weight)) form.weight = this.form.weight
                    if (!Array.isArray(form.passCondition)) form.passCondition = this.form.passCondition
                    this.classList = form.classList || []
                    Object.keys(this.form).forEach(k => {
                        this.form[k] = form[k]
                    })
                }
            })
        },
        getSubmitData () {
            const form = this.form
            return {
                ...form,
                weight: JSON.stringify(form.weight),
                passCondition: JSON.stringify(form.passCondition)
            }
        },
        submit () {
            this.$refs.form.validate(v => {
                if (v) {
                    const data = this.getSubmitData()
                    data.publish = 1
                    this.saveData(data)
                }
            })
        },
        submitSave () {
            this.$refs.form.validate(v => {
                if (v) {
                    const data = this.getSubmitData()
                    this.saveData(data)
                }
            })
        },
        saveData (data) {
            const fn = data.id ? updateTraining : addTraining
            fn(data).then(res => {
                if (res.data.code === '0000') {
                    this.$Message.success('操作成功')
                    this.nextPageReload()
                    this.cancel()
                } else {
                    this.$Message.success('操作失败')
                }
            })
        },
        cancel () {
            this.removeTagNav(this.$route)
            this.$router.replace({
                name: 'trainingList'
            })
        }
    }
}
</script>
<style lang="less" scoped>
.form-item {
    width: 50%;
    float: left;
}
.form-title {
    font-size: 14px;
    font-weight: 700;
}
.input-width {
    width: 300px;
}
.weight-setting {
    border: 1px solid #eee;
    line-height: 1.5;
    font-size: 0;
    display: inline-block;
    vertical-align: top;
    .weight--item {
        display: inline-block;
        vertical-align: top;
        font-size: 12px;
        + .weight--item {
            border-left: 1px solid #eee;
        }
    }
    .weight--label {
        padding: 6px 0;
        text-align: center;
        background-color: #f5f7f9;
        border-bottom: 1px solid #eee;
    }
    .weight--content {
        text-align: center;
        padding: 6px;
    }
}
.training-form {
    max-width: 1000px;
    .ivu-input-wrapper,
    .my-remote-search3,
    .ivu-select,
    .ivu-input-wrapper {
        max-width: 300px;
    }
    .ivu-date-picker {
        width: 300px;
    }
}

</style>
